package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.SkuImagesEntity;
import com.atguigu.gulimall.product.entity.SpuInfoDescEntity;
import com.atguigu.gulimall.product.entity.SpuInfoEntity;
import com.atguigu.gulimall.product.feign.SeckillFeignServcie;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.to.SeckillSkuInfo;
import com.atguigu.gulimall.product.vo.ItemAttrVo;
import com.atguigu.gulimall.product.vo.SkuItemVo;
import com.atguigu.gulimall.product.vo.SpuGroupName;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SkuInfoDao;
import com.atguigu.gulimall.product.entity.SkuInfoEntity;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {
    @Autowired
    SeckillFeignServcie seckillFeignServcie;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private SkuSaleAttrValueService saleAttrValueService;

    @Autowired
    private SpuInfoService spuInfoService;

    @Autowired
    private ThreadPoolExecutor threadPool;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        /**
         * key: '华为',//检索关键字
         * catelogId: 0,
         * brandId: 0,
         * min: 0,
         * max: 0
         */
        String key = (String) params.get("key");
        String catelogId = (String) params.get("catelogId");
        String brandId = (String) params.get("brandId");
        String min = (String) params.get("min");
        String max = (String) params.get("max");

        LambdaQueryWrapper<SkuInfoEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(StringUtils.isNotEmpty(key), item -> {
            item.eq(SkuInfoEntity::getSkuId, key)
                    .or()
                    .like(SkuInfoEntity::getSkuName, key);
        });
        wrapper.eq(StringUtils.isNotEmpty(catelogId) && !catelogId.equalsIgnoreCase("0"),
                        SkuInfoEntity::getCatalogId, catelogId)
                .eq(StringUtils.isNotEmpty(brandId) && !brandId.equalsIgnoreCase("0"),
                        SkuInfoEntity::getBrandId, brandId)
                .gt(StringUtils.isNotEmpty(min),SkuInfoEntity::getPrice,min)
                .lt(StringUtils.isNotEmpty(max)&&!max.equalsIgnoreCase("0"),SkuInfoEntity::getPrice,max);
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getBySpuId(Long spuId) {
        List<SkuInfoEntity> skuInfoEntities = this.list(new LambdaQueryWrapper<SkuInfoEntity>().eq(SkuInfoEntity::getSpuId, spuId));

        return skuInfoEntities;
    }

    @Override
    public SkuItemVo getItemBySkuId(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();
        CompletableFuture<Long> infoFuture = CompletableFuture.supplyAsync(() -> {
            //1.获取sku详细信息
            SkuInfoEntity skuInfo = this.getById(skuId);
            skuItemVo.setInfo(skuInfo);
            Long spuId = skuInfo.getSpuId();
            return spuId;
        });

        CompletableFuture<Void> attrFuture = infoFuture.thenAcceptAsync(r -> {
            //3.获取当前sku的所有spu销售属性
            List<ItemAttrVo> attrVos = saleAttrValueService.getAttrGroupsBySpuId(r);
            skuItemVo.setSkuSaleAttrs(attrVos);
        }, threadPool);

        CompletableFuture<Void> cataFuture = infoFuture.thenAcceptAsync(r -> {
            //4.获取spu的所有分组以及每个分组的基本属性
            //获取分类id
            SpuInfoEntity spuInfo = spuInfoService.getById(r);
            Long catalogId = spuInfo.getCatalogId();
            List<SpuGroupName> groupNames = attrGroupService.getGroupWithAttrsBySpuId(catalogId, r);
            skuItemVo.setGroupNames(groupNames);
        }, threadPool);

        CompletableFuture<Void> spuFuture = infoFuture.thenAcceptAsync(r -> {
            //5.获取spu的介绍信息
            SpuInfoDescEntity spuInfoDesc = spuInfoDescService.getSpuId(r);
            skuItemVo.setSpuDesc(spuInfoDesc.getDecript());
        });

        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            //2.获取sku图片信息
            List<SkuImagesEntity> images = skuImagesService.getBySkuId(skuId);
            skuItemVo.setImages(images);
        }, threadPool);

        //6.获取sku的秒杀信息
        CompletableFuture<Void> seckillFuture = CompletableFuture.runAsync(() -> {
            R r = seckillFeignServcie.seckillSku(skuId);
            if (r.getCode() == 0) {
                SeckillSkuInfo data = r.getData(new TypeReference<SeckillSkuInfo>() {
                });
                skuItemVo.setSeckill(data);
            }
        }, threadPool);


        CompletableFuture.allOf(attrFuture,cataFuture,spuFuture,imageFuture,seckillFuture).get();

        return skuItemVo;
    }

}